<template>
  <div class="poetry-grid">
    <div v-if="isLoading" class="text-center py-12">
      <div class="animate-spin w-12 h-12 border-4 border-primary-coral border-t-transparent rounded-full mx-auto mb-4"></div>
      <p class="text-text-secondary">正在加载古诗...</p>
    </div>
    
    <div v-else-if="filteredPoems.length === 0" class="text-center py-12">
      <div class="w-24 h-24 mx-auto mb-6 rounded-circle bg-gray-200 flex items-center justify-center">
        <img src="/images/icon_book_3.jpg" alt="未找到" class="w-12 h-12 opacity-50" />
      </div>
      <h3 class="text-xl font-bold text-text-primary mb-2">未找到古诗</h3>
      <p class="text-text-secondary">请尝试其他搜索关键词</p>
    </div>
    
    <div 
      v-else
      class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
    >
      <PoetryCard 
        v-for="poem in filteredPoems" 
        :key="poem.id" 
        :poem="poem" 
        @click="openPoetryDetail(poem.id)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import PoetryCard from '@/components/PoetryCard.vue'
import { usePoetryStore } from '@/stores/poetry'
import type { Poetry } from '@/types'

interface Props {
  searchQuery?: string
  selectedAuthor?: string
  selectedDynasty?: string
  selectedDifficulty?: string
  selectedTheme?: string
}

const props = withDefaults(defineProps<Props>(), {
  searchQuery: '',
  selectedAuthor: '',
  selectedDynasty: '',
  selectedDifficulty: '',
  selectedTheme: ''
})

const router = useRouter()
const poetryStore = usePoetryStore()

const isLoading = computed(() => poetryStore.isLoading)

const filteredPoems = computed(() => {
  let poems = poetryStore.poetryCollection?.poems || []
  
  // 按搜索词过滤
  if (props.searchQuery.trim()) {
    poems = poetryStore.searchPoems(props.searchQuery)
  }
  
  // 按作者过滤
  if (props.selectedAuthor) {
    poems = poems.filter(poem => poem.author === props.selectedAuthor)
  }
  
  // 按朝代过滤
  if (props.selectedDynasty) {
    poems = poems.filter(poem => poem.dynasty === props.selectedDynasty)
  }
  
  // 按难度过滤
  if (props.selectedDifficulty) {
    const difficultyPoems = poetryStore.getPoemsByDifficulty(props.selectedDifficulty)
    poems = poems.filter(poem => 
      difficultyPoems.some(dp => dp.id === poem.id)
    )
  }
  
  // 按主题过滤
  if (props.selectedTheme) {
    const themePoems = poetryStore.getPoemsByTheme(props.selectedTheme)
    poems = poems.filter(poem => 
      themePoems.some(tp => tp.id === poem.id)
    )
  }
  
  return poems
})

const openPoetryDetail = (poemId: number) => {
  router.push(`/poetry/${poemId}`)
}
</script>

<style scoped>
.poetry-grid {
  min-height: 400px;
}
</style>